package com.framework.boc.admin.security.service;

import com.framework.boc.admin.security.error.LoginErrorEnum;
import com.framework.boc.admin.security.models.AuthenticationRequestBody;
import com.framework.boc.admin.security.models.AuthenticationResponseBody;
import com.framework.boc.admin.security.utils.JwtUtil;
import com.framework.boc.error.CommonException;
import com.framework.boc.error.ErrorEnum;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class AuthenticateService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    MyUserDetailsService userDetailsService;

    @Autowired
    JwtUtil jwtUtil;

    /**
     * 验证
     */
    public AuthenticationResponseBody authenticate(AuthenticationRequestBody body) throws CommonException {
        try {
            authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(body.getUserName(), body.getPassword()));
        } catch (BadCredentialsException e) {
            logger.error("用户名密码错误");
            logger.error(e.getMessage());
            throw new CommonException(LoginErrorEnum.INCORRECT_USERNAME_PASSWORD);
        }

        final UserDetails userDetails = userDetailsService.loadUserByUsername(body.getUserName());
        List<String> authorities = userDetails.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.toList());
        String authoritiesStr = StringUtils.join(authorities, ",");
        Map<String, Object> claims = new HashMap<>();
        claims.put("authorities", authoritiesStr);
        final String jwt = jwtUtil.generateToken(userDetails, claims);
        return new AuthenticationResponseBody(jwt);
    }
}
